
(function()
{
	if($.moco == null)
	{
		var moco = {};
		$.moco = moco;
	}

	if($.moco.env == null)
	{
		$.moco.env = {};
	}

	var Dialog = function ()
	{
		this.id = Math.random() * 1000 + 7*3;

		this.dialog = null; // the dialog window (borders, header, body, footer)
		this.header = null;
		this.body = null;
		this.footer = null;

		this.modal = true;

		this.url = "";

		this.title = "";

		this.height = 300;
		this.width = 500;

		this.position = "top"; // allowed top or middle

		this.showOnLoad = false;

		this.onLoad = null;
		this.onClose = null;

		this.show = function(needLoad)
		{
			if($(window).scrollTop() > 50)
			{
				$('#' + this.id).css("top", ($(window).scrollTop() - 200 + "px"));
			}
			else
			{
				$('#' + this.id).css("top", (0 + "px"));
			}

			if((this.showOnLoad || needLoad) && this.url !== "")
			{
				$.moco.env['selectedId'] = this.id;

				$.ajax( { url: this.url, cache: false, type: "POST", 
							success: function (data) { 
									$('#'+$.moco.env['selectedId'] +' > div[class*="content"]').html(data); 

									if($.moco.dialogs[$.moco.env['selectedId']].onLoad != null)
									{
										$.moco.dialogs[$.moco.env['selectedId']].onLoad();
									}
							} } ); 
			}

			// hide other content
			$(".selector").css("display", "none");
			$(".selector").children("#"+this.id).parent().css("display", "");

			$('#grayBlock').css("display", "block");

			$("#"+this.id).show(); 
		};

		this.close = function()
		{
			$(".selector").css("display", "");

			$.moco.dialogs.hide();
			if(this.onClose != null)
			{
				this.onClose();
			}
		}
	}

	$(document).keypress(function(event) {

		if(event.keyCode == 27)
			$.moco.dialogs.hide(); 

	} );

	$.moco.dialogs = {};

	$.moco.dialogs = $.extend($.moco.dialogs, {

		count : 0,

		add : function (obj, options)
		{
		
			$.moco.dialogs.count++;

			if(obj != null)
			{
				$.moco.dialogs[obj.id] = obj;
			}
			else if(options != null)
			{
				dialog = new Dialog();
				dialog.id = options["id"];
				dialog.width = options["width"];
				dialog.height = options["height"];
				dialog.url = options["url"];
				dialog.showOnLoad = options["showOnLoad"];

				$('#' + dialog.id).css("left", ($(document).width()/2 - dialog.width/2) + "px");
				$('#' + dialog.id).css('width', dialog.width);
				$('#' + dialog.id).css('height', dialog.height);

				$.moco.dialogs[dialog.id] = dialog;
				$.moco.dialogs.count++;

				obj = dialog;
			}

			if($.moco.dialogs[dialog.id].showOnLoad)
			{
				$.moco.dialogs[dialog.id].show();
			}

			return $.moco.dialogs[obj.id];
		},

		hide : function ()
		{
			$(".selector").css("display", "");

			$('div[id*="dialog"]').css("display", "none");
			$('#grayBlock').css("display", "none");
		}

	});

})();